
package com.shop.cloud.mall.api.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.mall.api.mapper.PointsRecordMapper;
import com.shop.cloud.mall.api.mapper.SignConfigMapper;
import com.shop.cloud.mall.api.mapper.SignRecordMapper;
import com.shop.cloud.mall.api.service.*;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.mall.common.entity.*;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 签到记录
 *
 * @author
 * @date 2021-01-13 15:29:30
 */
@Service
@AllArgsConstructor
public class SignRecordServiceImpl extends ServiceImpl<SignRecordMapper, SignRecord> implements SignRecordService {

	private final SignConfigMapper signConfigMapper;
	private final UserPointsService userPointsService;
	private final PointsRecordMapper pointsRecordMapper;
	private final VipUserRechargeService vipUserRechargeService;
	private final VipRightsService vipRightsService;
	private final VipUserService vipUserService;

	@Override
	public SignRecord getSignRecord(String userId) {
		//获取用户的签到记录
		SignRecord signRecord = baseMapper.selectOne(Wrappers.<SignRecord>query().lambda()
				.eq(SignRecord::getUserId, userId));
		if(signRecord == null){//没有则新增
			signRecord = new SignRecord();
			signRecord.setUserId(userId);
			signRecord.setCumulateDays(0);
			signRecord.setContinuDays(0);
			baseMapper.insert(signRecord);
		}else if(signRecord.getUpdateTime() != null
				&& !signRecord.getUpdateTime().toLocalDate().equals(LocalDate.now())
				&& !signRecord.getUpdateTime().toLocalDate().equals(LocalDate.now().minusDays(1))){//判断当天是否是连续天数
			//最后签到时候不是今天和昨天，则清空连续天数
			signRecord.setContinuDays(0);
			baseMapper.updateById(signRecord);
		}
		if(signRecord.getUpdateTime() != null
				&& signRecord.getUpdateTime().toLocalDate().equals(LocalDate.now().minusDays(1))){//最后签到时间为昨天
			long count = signConfigMapper.selectCount(null);
			//昨天已经签满，则清空连续天数
			if(count == signRecord.getContinuDays()){
				signRecord.setContinuDays(0);
				baseMapper.updateById(signRecord);
			}
		}
		return signRecord;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@Klock(name = "userSign", keys = {"#userId"}, lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
	public SignConfig userSign(String userId) {
		//获取用户的签到记录
		SignRecord signRecord = this.getSignRecord(userId);
		//判断当天是否已经签到过
		if(signRecord.getUpdateTime() == null || !signRecord.getUpdateTime().toLocalDate().equals(LocalDate.now())){
			//获取签到配置
			Page page = new Page();
			page.setSearchCount(false);
			page.setSize(1);
			page.setCurrent(signRecord.getContinuDays()+1);
			List<OrderItem> orders = new ArrayList<>();
			OrderItem orderItem = new OrderItem();
			orderItem.setAsc(true);
			orderItem.setColumn("sort");
			page.setOrders(orders);
			List<SignConfig> listSignConfig = signConfigMapper.selectPage(page,null).getRecords();
			if(listSignConfig.size() <= 0){//已经签满，重头开始
				page.setCurrent(1);
				listSignConfig = signConfigMapper.selectPage(page,null).getRecords();
				if(listSignConfig.size() <= 0){
					throw new RuntimeException("请在后台设置签到信息");
				}else{
					//重置连续天数
					signRecord.setContinuDays(1);
				}
			}else{
				//连续天数+1
				signRecord.setContinuDays(signRecord.getContinuDays()+1);
			}
			SignConfig signConfig = listSignConfig.get(0);
			//累计天数+1
			signRecord.setCumulateDays(signRecord.getCumulateDays()+1);
			signRecord.setUpdateTime(LocalDateTime.now());
			baseMapper.updateById(signRecord);
			//更新用户积分
			userPointsService.updateUserPoints(userId,signConfig.getPosts(), true);
			//新增积分记录
			PointsRecord pointsRecord = new PointsRecord();
			pointsRecord.setRecordType(MallConstants.POINTS_RECORD_TYPE_7);
			pointsRecord.setUserId(userId);
			pointsRecord.setAmount(signConfig.getPosts());
			pointsRecord.setDescription("签到积分");
			//查询当前用户是否是会员
			VipUser vipUser = vipUserService.getByUserId(userId);
			if(vipUser != null){
				//是会员，则积分按配置翻倍
				VipRights vipRights = vipRightsService.getOne(Wrappers.<VipRights>query().lambda()
						.eq(VipRights::getVipTypeId,vipUser.getVipTypeId())
						.eq(VipRights::getEnable, CommonConstants.YES)
						.eq(VipRights::getType, MallConstants.VIPRIGHTS_TYPE_2));
				if(vipRights != null){
					pointsRecord.setAmount(signConfig.getPosts()*vipRights.getDiscount());
					pointsRecord.setDescription("签到积分，会员翻倍*"+vipRights.getDiscount());
				}
			}
			pointsRecordMapper.insert(pointsRecord);
			return signConfig;
		}else{
			return null;
		}
	}

}
